package com.example.maggie.meizinote.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.widget.Toast;

import com.example.maggie.meizinote.app.MApp;
import com.example.maggie.meizinote.mvp.model.entity.User;
import com.example.maggie.meizinote.mvp.ui.activity.HomeActivity;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.example.maggie.meizinote.mvp.contract.LoginContract;


@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View rootView) {
        super(model, rootView);
    }

    public void toHome() {
        mRootView.launchActivity(new Intent(mApplication, HomeActivity.class));
        mRootView.killMyself();
    }

    public void login(String account, String password) {
        BmobUser bu2 = new BmobUser();
        bu2.setUsername(account);
        bu2.setPassword(password);
        bu2.login(new SaveListener<BmobUser>() {
            @Override
            public void done(BmobUser bmobUser, BmobException e) {
                if (e == null) {
                    mRootView.showMessage("登录成功");
                    MApp.setUserId(bmobUser);
                    toHome();
                    //通过BmobUser user = BmobUser.getCurrentUser()获取登录成功后的本地用户信息
                    //如果是自定义用户对象MyUser，可通过MyUser user = BmobUser.getCurrentUser(MyUser.class)获取自定义用户信息
                } else {
                    if (e.getErrorCode() == 101) mRootView.showMessage("用户名或密码不正确");
                    else if (e.getErrorCode() == 9018) mRootView.showMessage("用户名不能为空");
                    else mRootView.showMessage(e + "");
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

}
